package com.cedarhd.brzx.demo;

import org.apache.commons.lang.StringUtils;
import net.sf.json.JSONObject;
import com.bfd.facade.MerchantServer;
import com.bfd.util.PropertiesUtil;

public class HainaApiTest{
	
	private static String userName = "账号";
	private static String pwd = "密码";
	private static String apiCode = "您的apicode";
	
	private static volatile String tokenid;
	private static MerchantServer ms=new MerchantServer();
	
	public static String getTokenid(){
		if(StringUtils.isBlank(tokenid)){
			synchronized (HainaApiTest.class) {
				if(StringUtils.isBlank(tokenid)){
					tokenid = generateTokenid();
				}
			}
		}
		return tokenid;
	}
	
	private static String generateTokenid(){
		String tokenid = "";
		try {
			//登陆
			String login_res_str = ms.login(userName, pwd, "LoginApi", apiCode);
    		if(StringUtils.isNotBlank(login_res_str)){
    			JSONObject loginJson=JSONObject.fromObject(login_res_str);
    			if(loginJson.containsKey("tokenid")){
    				tokenid = loginJson.getString("tokenid");
    			}else{
    				System.out.println("返回结果异常，无tokenid！结果为："+login_res_str);
    			}
    		}
        } catch (Exception e) {
           	e.printStackTrace();
        }
		return tokenid;
	}
	
	public static String getBrData(String jsonData){
		String res = "";
		try {
			res = ms.getApiData(jsonData, apiCode);
			if(StringUtils.isNotBlank(res)){
				JSONObject json = JSONObject.fromObject(res);
				if(json.containsKey("code")&&json.getString("code").equals("100007")){
					tokenid = null;
					jsonData = JSONObject.fromObject(jsonData).put("tokenid", getTokenid()).toString();
					res = ms.getApiData(jsonData,apiCode);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	
	public static void main(String[] args) {
			JSONObject jso = new JSONObject();
			JSONObject reqData = new JSONObject();
			jso.put("apiName", "HainaApi");
			jso.put("tokenid", HainaApiTest.getTokenid());
			reqData.put("meal", "EduLevel");
			reqData.put("id", "140502198811102244");
			reqData.put("cell", "13986671110");
			reqData.put("name", "王亮");
			jso.put("reqData", reqData);
			String result = getBrData(jso.toString());
			System.out.println(result);
	}
}
